package app.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

import spark.*;

public class RequestUtil {

    public static String getQueryLocale(Request request) {
        return request.queryParams("locale");
    }
    
    public static String getParamBookName(Request req) {
    	String bookName = req.queryParams("bookname");
    	if (bookName == null) {
    		return "";
    	}
    	return bookName.strip();
    }
    
    public static String getParamDateSelected(Request req) {
    	String dateSelected = req.queryParams("dateselected");
    	String dateSelectedInAttr = req.session().attribute("dateselected");
    	DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
    	if (dateSelected == null || dateSelected.isBlank() ) {
    		if (dateSelectedInAttr == null || dateSelectedInAttr.isBlank()) {
    			dateSelected = LocalDate.now().format(formatter);
    			req.session().attribute("dateselected", dateSelected);
			} else {
    			dateSelected = dateSelectedInAttr;
			}
		} else {
    		try {
    			LocalDate d = LocalDate.parse(dateSelected, formatter);
    			dateSelected = d.format(formatter);
    		} catch (DateTimeParseException e) {
    			dateSelected = LocalDate.now().format(formatter);
    		}
    		req.session().attribute("dateselected", dateSelected);
		}
		return dateSelected.strip();
	}
    
    public static String getParamBookID(Request req) {
    	String bookId = req.queryParams("bookid");
    	if (bookId == null) {
    		bookId = "";
		}
    	return bookId.strip();
    }
    
    public static String getParamBookCategory(Request req) {
    	String bookCat = req.queryParams("bookcategory");
		if (bookCat == null) {
			bookCat = "";
		}
    	return bookCat.strip();
    }

    public static String getParamDateStart(Request req) {
		String dateStart = req.queryParams("datestart");
		if (dateStart == null) {
			dateStart = "";
		}
		return dateStart.strip();
	}

	public static String getParamDateEnd(Request req) {
		String dateEnd = req.queryParams("dateend");
		if (dateEnd == null) {
			dateEnd = "";
		}
		return dateEnd.strip();
	}

	public static String getParamDate(Request req) {
		String date = req.queryParams("date");
		if (date == null) {
			date = "";
		}
		return date.strip();
	}
}

